package com.zhentao.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexOperations;

/**
 * MongoDB配置类
 * 用于创建索引优化查询性能
 */
@Configuration
public class MongoConfig implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(MongoConfig.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void run(String... args) throws Exception {
        createChatMessageIndexes();
    }

    /**
     * 创建聊天消息集合的索引
     */
    private void createChatMessageIndexes() {
        IndexOperations indexOps = mongoTemplate.indexOps("chat_messages");

        // 1. 会话ID + 时间索引（主要查询索引）
        Index conversationTimeIndex = new Index()
                .on("conversationId", Sort.Direction.ASC)
                .on("timestamp", Sort.Direction.DESC)
                .on("isDeleted", Sort.Direction.ASC)
                .named("idx_conversation_time");
        indexOps.ensureIndex(conversationTimeIndex);

        // 2. 复合索引：fromName + toName + timestamp（兼容旧查询）
        Index conversationHistoryIndex = new Index()
                .on("fromName", Sort.Direction.ASC)
                .on("toName", Sort.Direction.ASC)
                .on("timestamp", Sort.Direction.DESC)
                .named("idx_conversation_history");
        indexOps.ensureIndex(conversationHistoryIndex);

        // 3. 复合索引：toName + isRead + isDeleted（用于查询未读消息）
        Index unreadMessagesIndex = new Index()
                .on("toName", Sort.Direction.ASC)
                .on("isRead", Sort.Direction.ASC)
                .on("isDeleted", Sort.Direction.ASC)
                .named("idx_unread_messages");
        indexOps.ensureIndex(unreadMessagesIndex);

        // 4. 会话ID索引（快速定位对话）
        Index conversationIdIndex = new Index()
                .on("conversationId", Sort.Direction.ASC)
                .named("idx_conversation_id");
        indexOps.ensureIndex(conversationIdIndex);

        // 5. 时间索引（用于按时间排序）
        Index timestampIndex = new Index()
                .on("timestamp", Sort.Direction.DESC)
                .named("idx_timestamp");
        indexOps.ensureIndex(timestampIndex);

        // 6. 用户索引（用于查询用户所有相关消息）
        Index fromUserIndex = new Index()
                .on("fromName", Sort.Direction.ASC)
                .on("isDeleted", Sort.Direction.ASC)
                .named("idx_from_user");
        indexOps.ensureIndex(fromUserIndex);

        Index toUserIndex = new Index()
                .on("toName", Sort.Direction.ASC)
                .on("isDeleted", Sort.Direction.ASC)
                .named("idx_to_user");
        indexOps.ensureIndex(toUserIndex);

        // 7. 消息类型索引（用于按类型筛选）
        Index messageTypeIndex = new Index()
                .on("messageType", Sort.Direction.ASC)
                .on("timestamp", Sort.Direction.DESC)
                .named("idx_message_type");
        indexOps.ensureIndex(messageTypeIndex);

        log.info("MongoDB聊天消息索引创建完成");
    }
}